package com.example.callmanagerandroid;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.example.database.Contact;
import com.example.internet.Internet;
import com.example.user.User;

public class MainActivity extends Activity implements OnClickListener {

	private Button syn, login, back, sms;
	private EditText link, user, pass, line, linkPushNumber;
	private ProgressDialog dialog = null;
	private int pageSum = 0;
	private int currentPageDownload = 1;
	private ProgressDialog dialogs;
	private CheckBox check;
	public static final String MyPREFERENCES = "mycallappshare";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.layout);

		syn = (Button) findViewById(R.id.button1);
		syn.setOnClickListener(this);
		login = (Button) findViewById(R.id.button2);
		login.setOnClickListener(this);
		back = (Button) findViewById(R.id.button3);
		back.setOnClickListener(this);
		check = (CheckBox) findViewById(R.id.checkBox1);
		sms = (Button) findViewById(R.id.button4);
		sms.setOnClickListener(this);

		link = (EditText) findViewById(R.id.editText1);
		user = (EditText) findViewById(R.id.editText2);
		pass = (EditText) findViewById(R.id.editText3);
		line = (EditText) findViewById(R.id.editText4);
		linkPushNumber = (EditText) findViewById(R.id.editText5);

		dialog = new ProgressDialog(MainActivity.this);
		dialog.setMessage("đang tải dữ liệu...");
		dialog.setIndeterminate(false);
		dialog.setCancelable(false);

		dialogs = new ProgressDialog(MainActivity.this);
		dialogs.setTitle("Cấu hình ...");
		dialogs.setMessage("Vui lòng đợi tải dữ liệu ...");
		dialogs.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialogs.setCancelable(false);
		
		if(getShare())
			check.setChecked(true);
		else
			check.setChecked(false);
		
		check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				sharePre(isChecked);
			}
		});

		loadData();
	}
	
	private void sharePre(Boolean isShow){
		SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, this.MODE_PRIVATE);
		Editor editor = sharedpreferences.edit();
		editor.putBoolean("share", isShow);
		editor.commit();
	}
	
	
	private Boolean getShare(){
		SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, this.MODE_PRIVATE);
		Boolean isShow = sharedpreferences.getBoolean("share", true);
		return isShow;
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		loadData();
	}

	@Override
	public void onClick(View v) {
		if (v == syn) {
			Internet internet = new Internet(getApplicationContext());
			if (internet.Check()) {
				if (!user.getText().toString().equals("")
						&& !link.getText().toString().equals("")
						&& !user.getText().toString().equals("")
						&& !pass.getText().toString().equals("")) {
					GetDataFromWebSite getData = new GetDataFromWebSite();
					String url = link.getText().toString() + "mUserName="
							+ user.getText().toString() + "&mPassword="
							+ pass.getText().toString() + "&mPageNumber=0";
					getData.execute(url);
				} else {
					alertConfirm("Dữ liệu không được bỏ trống");
				}
			}
		} else if (v == login) {
			Contact contact = new Contact(getApplicationContext());
			if (!user.getText().toString().equals("")
					&& !pass.getText().toString().equals("")
					&& !line.getText().toString().equals("")
					&& !linkPushNumber.getText().toString().equals("")
					&& !link.getText().toString().equals("")) {
				contact.deleteUser();
				contact.insertUser(line.getText().toString(), user.getText()
						.toString(), pass.getText().toString(), linkPushNumber
						.getText().toString(), link.getText().toString());
				// alert thanh cong
				alertConfirm("Đã lưu thành công");
			} else {
				// alert canh bao
				alertConfirm("Dữ liệu không được bỏ trống");
			}
			contact.close();
			loadData();

		} else if (v == back) {
			Intent intent = new Intent(MainActivity.this,
					CallListActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			finish();
		} else if(v == sms){
			Intent intent = new Intent(MainActivity.this, QuanLiDauSo.class);
			startActivity(intent);
		}
	}

	private void loadData() {
		Contact contact = new Contact(getApplicationContext());
		Cursor c = contact.selectUser();
		if (c != null) {
			if (c.moveToFirst()) {
				String name = c.getString(c.getColumnIndexOrThrow("Username"));
				String pasS = c.getString(c.getColumnIndexOrThrow("Pass"));
				String liNe = c.getString(c.getColumnIndexOrThrow("Line"));
				String liNePushPhone = c.getString(c
						.getColumnIndexOrThrow("url"));
				String links = c.getString(c.getColumnIndexOrThrow("link"));
				user.setText(name);
				pass.setText(pasS);
				line.setText(liNe);
				linkPushNumber.setText(liNePushPhone);
				link.setText(links);
				Log.w("", "**********************");
				Log.w("", name);
				Log.w("", pasS);
				Log.w("", links);
			}
		} else {
			Log.w("", "Null");
		}
		c.close();
		contact.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private class GetDataFromWebSite extends AsyncTask<String, Boolean, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			Looper.prepare();
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(params[0]);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String response_str = "******";

			try {
				response_str = client.execute(request, responseHandler);
			} catch (ClientProtocolException e) {
				dialog.dismiss();
				alertConfirm("Tải dữ liệu không thành công");
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				dialog.dismiss();
				alertConfirm("Tải dữ liệu không thành công");
				e.printStackTrace();
				return null;
			}
			return response_str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dialog.dismiss();
			if (result != null) {
				String str = "<string xmlns=\"http://microsoft.com/webservices/\">";
				String[] strs = result.split(str);
				if (strs.length == 2) {
					String[] strss = strs[1].split("</");
					if (strss.length == 2) {
						pageSum = Integer.parseInt(strss[0]);
						dialog.show();
						Contact contact = new Contact(getApplicationContext());
						contact.DeleteName();
						contact.close();
						dialog.dismiss();
						dialogs.setProgress(0);
						dialogs.setMax(pageSum);
						dialogs.show();
						startAsntask();
					} else {
						alertConfirm("Tải dữ liệu không thành công");
					}
				} else {
					alertConfirm("Tải dữ liệu không thành công");
				}
				// if (strs.length == 2) {
				// Log.w(String.valueOf(strs.length), strs[1]);
				// try {
				// JSONObject object = new JSONObject(strs[1]);
				// exportUser(getJsonArray(object));
				// dialog.dismiss();
				// alertConfirm("Hoàn tất tải dữ liệu");
				// } catch (JSONException e) {
				// dialog.dismiss();
				// alertConfirm("Tải dữ liệu không thành công");
				// e.printStackTrace();
				// }
				// } else {
				// dialog.dismiss();
				// alertConfirm("Tải dữ liệu không thành công");
				// }
			}
		}

		private class GetUserFromU extends AsyncTask<String, Boolean, String> {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dialogs.setProgress(currentPageDownload);

			}

			@Override
			protected String doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(params[0]);
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String response_str = "******";

				try {
					response_str = client.execute(request, responseHandler);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					return null;
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
				return response_str;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (result != null) {
					String str = "<string xmlns=\"http://microsoft.com/webservices/\">";
					String[] strs = result.split(str);
					if (strs.length == 2) {
						try {
							JSONObject object = new JSONObject(strs[1]);
							exportUser(getJsonArray(object));
							currentPageDownload++;
							if (currentPageDownload <= pageSum) {
								startAsntask();
							} else {
								dialogs.dismiss();
								alertConfirm("Hoàn tất tải dữ liệu");
							}
						} catch (JSONException e) {
							e.printStackTrace();
							startAsntask();
						}
					} else {
						startAsntask();
					}
				} else {
					startAsntask();
				}
			}
		}

		private void startAsntask() {
			GetUserFromU get = new GetUserFromU();
			GetDataFromWebSite getData = new GetDataFromWebSite();
			String url = link.getText().toString() + "mUserName="
					+ user.getText().toString() + "&mPassword="
					+ pass.getText().toString() + "&mPageNumber="
					+ currentPageDownload;
			get.execute(url);
		}

		private JSONArray getJsonArray(JSONObject object) {
			JSONArray array = new JSONArray();
			try {
				array = object.getJSONArray("khachhang");
			} catch (JSONException e) {
				e.printStackTrace();
				alertConfirm("Tải dữ liệu không thành công");
			}
			return array;
		}

		private void exportUser(JSONArray array) {
			List<User> userList = new ArrayList<User>();
			for (int i = 0; i < array.length(); i++) {
				User user = new User();
				String KhID = "";
				String Ma = "";
				String Ten = "";
				String DiaChi = "";
				String DienThoai = "";
				String TrangThai = "";

				try {
					JSONObject obj = array.getJSONObject(i);
					KhID = obj.getString("KhID");
					Ma = obj.getString("Ma");
					Ten = obj.getString("Ten");
					DiaChi = obj.getString("DiaChi");
					DienThoai = obj.getString("DienThoai");
					TrangThai = obj.getString("GhiChu");
				} catch (JSONException e) {
					e.printStackTrace();
					dialog.dismiss();
					alertConfirm("Tải dữ liệu không thành công");
				}

				user.setKHID(KhID);
				user.setMA(Ma);
				user.setTEN(Ten);
				user.setDIACHI(DiaChi);
				user.setDIENTHOAI(DienThoai);
				user.setTRANGTHAI(TrangThai);
				userList.add(user);
			}

			addUserToDatabase(userList);
		}

		private void addUserToDatabase(List<User> userList) {
			Contact contact = new Contact(getApplicationContext());
			for (int i = 0; i < userList.size(); i++) {
				User user = userList.get(i);
				contact.insertName(user.getKHID(), user.getMA(), user.getTEN(),
						user.getDIACHI(), user.getDIENTHOAI(),
						user.getTRANGTHAI());
			}
			contact.close();
		}
	}

	private void alertConfirm(String mess) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				MainActivity.this);
		alertDialogBuilder.setTitle("Thông báo");
		alertDialogBuilder
				.setMessage(mess)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
								Intent intent = new Intent(MainActivity.this,
										MainActivity.class);
								startActivity(intent);
								MainActivity.this.finish();
							}
						});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}